<template>
    <div class="app-container">
        <levelbar></levelbar>
          <div class="table-title">
            <el-form :model="classIdInfofamily" slot="form" label-width="80px">
                <div class="title margin-row margin-text">班级信息</div>
                <el-row :gutter="20" type="flex" justify="space-around" class="margin-row">
                    <el-col :span="6">
                        <div class="title-describe" v-cloak> <span>班级名称:</span>{{classIdInfofamily.className}}</div>
                    </el-col>
                    <el-col :span="6" v-if="classIdInfofamily.gradeName">
                        <div class="title-describe" v-cloak> <span>年级:</span>{{classIdInfofamily.gradeName}}</div>
                    </el-col>
                    <el-col :span="6">
                        <div class="title-describe" v-cloak> <span>班级编号:</span>{{classIdInfofamily.classNum}}</div>
                    </el-col>
                    <el-col :span="6">
                        <div class="title-describe" v-cloak> <span>班级码:</span>{{classIdInfofamily.classCode}}</div>
                    </el-col>
                </el-row>
              <div class="border-center"></div>
              <!-- <div class="table-title" slot="table-title"> -->
                <div class="margin-row margin-button">
                  <span class="table-title-span">
                    <el-button @click="addNewClass">新增</el-button>
                    <el-button @click="allJustment">集体调班</el-button>
                    <el-button @click="btnImport">批量导入</el-button>
                    <el-button @click="delTab">批量删除</el-button>
                  </span>
                </div>
                  
                  <!-- <el-button @click="leaveBtn">离班</el-button> -->
              <!-- </div> -->
              <div class="margin-row">
                <el-table :data="studentList" border tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange" v-loading="loading">
                  <el-table-column type="selection">
                  </el-table-column>
                  <!-- <el-table-column type="index" label="序号" align="center">
                  </el-table-column> -->
                  <el-table-column label="学生姓名" prop="studentName" show-overflow-tooltip align="center">
                  </el-table-column>
                  <el-table-column label="e学云ID号" prop="exueCode" show-overflow-tooltip align="center">
                    <template scope="scope">
                      {{!scope.row.exueCode ? '--' : scope.row.exueCode}}
                    </template>
                  </el-table-column>
                  <el-table-column label="性别" align="center">
                    <template scope="scope">
                          {{scope.row.sex == 0 ? '男' : scope.row.sex == 1 ? '女' : '未设置'}}
                    </template>
                  </el-table-column>
                  <el-table-column label="绑定家长数" prop="parentNum" show-overflow-tooltip align="center">
                    <template scope="scope">
                      {{!scope.row.parentNum ? '--' : scope.row.parentNum}}
                    </template>
                  </el-table-column>
                  <el-table-column label="最后登陆时间" show-overflow-tooltip align="center">
                    <template scope="scope">
                          {{!scope.row.lastLoginTime ? '--' : scope.row.lastLoginTime}}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="left">
                      <template scope="scope">
                          <el-button type="text" class="btn-success" @click="btnSee(scope.row)">查看</el-button>
                          <el-button type="text" class="btn-success" @click="adjustment(scope.row)">调班</el-button>
                          <el-button type="text" class="btn-success" @click="delClass(scope.row)">删除</el-button>
                      </template>
                  </el-table-column>
              </el-table>
              <div class="pagination-container" style="text-align:right">
                  <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total" :current-page.sync="listQuery.page" :page-sizes="config.pageSizes" :page-size="config.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                  </el-pagination>
              </div>
              </div>
            </el-form>
          </div>
        <!-- 调班 -->
        <adjustmentDialog @adjustmentSon="adjustmentSon" v-if="adjustmentData.dialogFormVisible" :adjustmentData="adjustmentData"></adjustmentDialog>

        <!-- 批量导入 -->
        <importBatch @importData="importData" v-if="importList.dialogFormVisible" :importList="importList"></importBatch>

        <!-- 离班 -->
        <!-- <el-dialog title="提示" :visible.sync="leaveData.dialogFormVisible" size="tiny">
            <span>确定离开该班级？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="leaveCancel">取 消</el-button>
                <el-button type="primary" @click="leaveConfirm">确 定</el-button>
            </span>
        </el-dialog> -->

        <!-- created by cuihd at 20180709 优化集体调班/批量导入学生 添加进度条-->
        <el-dialog :title="dialogTitle" size="tiny" :visible.sync="dialogTimeout">
            <el-progress v-if="progress == '100'" :percentage="progress" status="success"></el-progress>
            <el-progress v-else :percentage="progress"></el-progress>
        </el-dialog>
    </div>
</template>
<script>
import Levelbar from "../layout/Levelbar";
import TableLayout from "components/TableLayout";
import { mapState, mapActions, mapGetters } from "vuex";
import { findStudentClassInfosByPage, removeStudent, shiftStudent, findClassInfoByClassId, changeStudentClassProgress, importStudentProgress, removeStudentProgress} from "api/classAll";
import adjustmentDialog from "./comps/adjustmentDialog";
import importBatch from "./comps/importBatch";

export default {
  name:"studentList",
  components: { Levelbar, TableLayout, adjustmentDialog, importBatch },
  created() {
    this.getstudentList();
    this.findInfoClassId();
  },
  watch: {// 局部刷新列表
        cacheUpdated(val) {
            val && this.getstudentList();
        }
  },
  computed: {
    ...mapState({
      config: state => state.config.table,
      cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表
    }),
    ...mapGetters(["uid"])
  },
  data() {
    return {
      //班级信息集合
      classIdInfofamily: {},
      loading: true,
      listQuery: {
        //分页
        page: 1,
        total: 0
      },

      //表单数据集合
      studentList: [],

      //调班子组件
      adjustmentData: {
        dialogFormVisible: false,
        id: null,
        family: {}
      },

      //批量导入子组件
      importList: {
        dialogFormVisible: false,
        classId: ""
      },

      //多选集合
      multipleSelection: [],

      //离班子组件状态
      leaveData: {
        dialogFormVisible: false
      },
       /**
       * created by cuihd at 20180709
       * 优化批量删除教师
       * 添加相关变量
       */
      dialogTitle: '正在集体调班...',
      dialogTimeout: false,
      progress: 0
    };
  },
  methods: {
    //全局获取行数
    ...mapActions(["ChangePageSize"]),
    handleSizeChange(val) {
      this.listQuery.page = 1;
      this.loading = true;
      this.listQuery.page = 1;
      this.ChangePageSize(val);
      this.getstudentList();
    },
    findInfoClassId() {
      findClassInfoByClassId(this.$route.params.id).then(data => {
        this.classIdInfofamily = data.data.content;
        this.schoolId = this.classIdInfofamily.schoolId;
      });
    },
    handleCurrentChange(val) {
      this.loading = true;
      this.listQuery.page = val;
      this.getstudentList();
    },
    getstudentList() {
      this.loading = true;
      findStudentClassInfosByPage(
        this.listQuery.page,
        this.config.pageSize,
        this.$route.params.id
      ).then(response => {
        this.loading = false;
        if (!response.data.content) {
          return false;
        } else {
          this.studentList = response.data.content.list;
          this.listQuery.total = response.data.content.pagination.total;
        }
      });
    },
    btnSee(val) {
      //跳转到学生管理
      this.$router.push({ path: `/studentManage/studentInforPage/${val.studentId}/${this.$route.params.id}`});
    },
    adjustment(val) {
      this.adjustmentData.id = [val.studentId];
      if (this.adjustmentData.id.length == 0) {
        this.$message({
          message: "请选择调班的学生",
          type: "warning"
        });
      } else {
        this.adjustmentData.dialogFormVisible = true;
        this.adjustmentData.family = this.classIdInfofamily;
      }
    },
    allJustment() {
      this.adjustmentData.id = this.tabFilter("studentId");
      if (this.adjustmentData.id == 0) {
        this.$message({
          message: "请选择调班的学生",
          type: "warning"
        });
      } else {
        this.adjustmentData.dialogFormVisible = true;
        this.adjustmentData.family = this.classIdInfofamily;
      }
    },
    adjustmentSon(val) {
      if (val.isTrue) {
        this.loading = true;
        this.adjustmentData.dialogFormVisible = false;
        this.dialogTitle = '正在调班中...';
        this.dialogTimeout = true;
        this.progress = 0;
        this.batchProgress(val);       
      }else{
        this.getstudentList();
      }
    },
    // created by cuihd at 20180711
    // 轮询接口获取未处理的数量
    batchProgress(obj) { // 递归轮询
        let totalNum = Number(obj.totalNum); // 强转成number类型
        changeStudentClassProgress(obj.timeStamp, obj.fromClassId, obj.toClassId).then(res => {
            if(res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null){
                if (res.data.content != 0) {
                    this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                    setTimeout(() => {
                        this.batchProgress(obj);
                    }, 1000);
                } else {
                    this.dialogTitle = '调班成功';
                    this.progress = 100;
                    setTimeout(() => {                       
                        this.dialogTimeout = false;
                        this.getstudentList();
                    }, 500)
                }
            }else{
                this.dialogTimeout = false;
                this.$message({
                    message: '调班失败！',
                    type: 'error'
                });
                this.getstudentList();
            }          
        }).catch(err => {
            console.log(err);
        })
    },
    // created by cuihd at 20180711
    // 轮询接口获取未导入学生的数量
    batchImportProgress(obj) { // 递归轮询
        let totalNum = Number(obj.totalNum); // 强转成number类型
        importStudentProgress(obj.timeStamp, obj.classId).then(res => {
            if(res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null){
                if (res.data.content != 0) {
                    this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                    setTimeout(() => {
                        this.batchImportProgress(obj);
                    }, 1000);
                } else {
                    this.dialogTitle = '批量导入成功';
                    this.progress = 100;
                    setTimeout(() => {                       
                        this.dialogTimeout = false;
                        this.getstudentList();
                    }, 500)
                }
            }else{
                this.dialogTimeout = false;
                this.$message({
                    message: '批量导入失败！',
                    type: 'error'
                });
                this.getstudentList();
            }          
        }).catch(err => {
            console.log(err);
        })
    },
    delClass(val) {
      this.$confirm("确定删除该学生吗？", " ", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
        // type: "warning"
      })
        .then(() => {
          let delId = [];
          delId.push(val.studentClassMapId);
          this.loading = true;
          removeStudent(delId).then(data => {
            this.loading = false;
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.getstudentList();
          }).catch(e =>{
            this.loading = false
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    addNewClass() {
      this.$router.push({
        path: `/classStudent/addNewStudent/${this.classIdInfofamily.schoolId}/${this.classIdInfofamily.classId}/${this.$route.params.id}`,
        // params: {
        //   schoolId: this.classIdInfofamily.schoolId,
        //   classId: this.classIdInfofamily.classId,
        //   id: this.$route.params.id
        // }
      });
    },
    btnImport() {
      this.importList.dialogFormVisible = true;
      this.importList.classId = this.$route.params.id;
    },
    importData(val) {
      if (val.isTrue) {
        this.adjustmentData.dialogFormVisible = false;
        this.dialogTitle = '正在批量导入学生...';
        this.dialogTimeout = true;
        this.progress = 0;
        this.batchImportProgress(val);
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delTab() {
      let studentIdArry = this.tabFilter("studentClassMapId");
      if(studentIdArry.length == 0){
        this.$message({
          message: "请选择删除的学生",
          type: "warning"
        });
      }else{
        this.$confirm("将删除选中学生，是否继续？", " ", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: " "
        }).then(() => {
          this.loading = true
          removeStudent(studentIdArry).then(res => {
            /**
             * created by cuihd at 20180711
             * 优化批量删除学生
             * 添加相关变量
             */
            let timeStamp = res.data.content.timeStamp;
            let totalNum = res.data.content.totalNum;
            this.dialogTitle = '正在批量删除学生...';
            this.dialogTimeout = true;
            this.progress = 0;
            this.batchDelProgress(timeStamp, totalNum);
          }).catch(e =>{
            this.loading = false
          })
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
      }
    },
    // created by cuihd at 20180711
    // 轮询接口获取未删除学生的数量
    batchDelProgress(timeStamp, totalNum) { // 递归轮询
        totalNum = Number(totalNum); // 强转成number类型
        removeStudentProgress(timeStamp).then(res => {
            if(res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null){
                if (res.data.content != 0) {
                    this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                    setTimeout(() => {
                        this.batchDelProgress(timeStamp, totalNum);
                    }, 1000);
                } else {
                    this.btnLoading = false;
                    this.dialogTitle = '批量删除成功';
                    this.progress = 100;
                    setTimeout(() => {                       
                        this.dialogTimeout = false;
                        this.getstudentList();
                    }, 500)
                }
            }else{
                this.dialogTimeout = false;
                this.$message({
                    message: '批量删除失败！',
                    type: 'error'
                });
                this.getstudentList();
            }          
        }).catch(err => {
            console.log(err);
        })
    },

    tabFilter(val) {
      let idList = [];
      this.multipleSelection.forEach(item => {
        idList.push(item[val]);
      });
      return idList;
    }
  }
};
</script>
<style lang="scss" scoped>
.margin-button{
  margin-bottom: 15px;
}
.table-title{
  padding: 20.5px 0;
  background: #fff;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
}
.margin-row{
  padding: 0 20px;
}
.margin-text{
 padding-left: 40px 
}
.border-center{
  height: 1px;
  background: #dddddd;
  margin: 30px 0 15px;
}
.title-describe{
  font-size: 14px;
  span{
    margin-right: 30px;
    color: #999999;
    margin-left: 18px;
  }
}
.title{
  position: relative;
  margin-bottom: 30px;
  font-size: 14px;
  &::after{
    content:'';
    position: absolute;
    left: 20px;
    top: 2px;
    width: 4px;
    height: 14px;
    background: #ff5e2c;
  }
}
.app-container {
  position: relative;
  padding: 20px 20px 10px;
  .app-levelbar {
    height: 35px;
  }
  .el-form {
    background: #fff;
    // padding-bottom: 50px;
  }
}
</style>
